package com.example.order.controller;

import com.example.order.Vo.ResponseVo;
import com.example.order.converter.OrderForm2OrderDTO;
import com.example.order.dto.OrderDTO;
import com.example.order.form.OrderForm;
import com.example.order.service.OrderService;
import com.example.order.utils.ResponseVoUtils;
import com.example.product.client.ProductClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/6/12 19:55
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 注入自己定义的 ProductClient
    @Autowired
    private ProductClient productClient;

    /**
     * 1. 参数校验
     * 2. 查询商品信息(调用商品微服务)
     * 3. 计算总价
     * 4. 扣库存(调用商品微服务)
     * 5. 订单入库
     */
    @PostMapping("/create")
    public ResponseVo create(@RequestBody  @Valid OrderForm orderForm) {
        // orderForm 转换为 orderDto
        OrderDTO orderDTO = OrderForm2OrderDTO.convert(orderForm);

        // 验证购物车是否有商品
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            return ResponseVoUtils.errorMessage("购物车不能为空");
        }



        OrderDTO result = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("orderId",result.getOrderId());
        return ResponseVoUtils.success(map);
    }



}
